package com.xxwy.ddu.common.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.xxwy.ddu.common.exception.HttpCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;

import java.util.List;
import java.util.Map;

/**
 * @author xxwy
 * on 2018/7/30 0030
 */
public class RUtil {

    private static final Logger logger = LoggerFactory.getLogger(RUtil.class);


    /**
     * 基类返回参数代码
     * @return
     */
    protected static ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, String code, String msg, Object data) {
        if (data != null) {
            if (data instanceof Page <?>) {
                Page<?> page = (Page<?>)data;
                modelMap.put("count", page.getTotal());
                modelMap.put("data", page.getRecords());
            } else if (data instanceof List<?>) {
                modelMap.put("data", data);
                modelMap.put("count", ((List<?>)data).size());
            } else {
                modelMap.put("data", data);
            }
        }
        modelMap.put("code", code);
        modelMap.put("msg", msg);
        modelMap.put("timestamp", System.currentTimeMillis());
        logger.info("response==>{}", JSON.toJSONString(modelMap));
        return ResponseEntity.ok(modelMap);
    }


    /**
     * 最基本的返回
     * @return
     */
    public static ResponseEntity<ModelMap> success(){
        return setModelMap(HttpCode.OK);
    }

    /**
     * 最基本的返回 + 数据
     * @param date
     * @return
     */
    public static ResponseEntity<ModelMap> success(Object date){
        return setModelMap(HttpCode.OK,date);
    }

    /**
     * 不知道要用这么做什么嘛
     * @param modelMap
     * @return
     */
    protected static ResponseEntity<ModelMap> success(ModelMap modelMap) {
        return setModelMap(modelMap,HttpCode.OK, null);
    }

    protected static ResponseEntity<ModelMap> failed(ModelMap modelMap){

        return setModelMap(modelMap,HttpCode.OK, null);
    }

    protected static ResponseEntity<ModelMap> setModelMap(Integer code) {
        return setModelMap(new ModelMap(), code, null);
    }

    protected static ResponseEntity<ModelMap> setModelMap(Integer code, Object data) {
        return setModelMap(new ModelMap(), code, data);
    }

    protected static ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, Integer code, Object data) {
        return setModelMap(modelMap, code.toString(), HttpCode.msg(code), data);
    }
}
